package org.qiandaosystem.qiandaosystemsource.service;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.qiandaosystem.qiandaosystemsource.common.ApiResponse;
import org.qiandaosystem.qiandaosystemsource.entity.Student;
import org.qiandaosystem.qiandaosystemsource.entity.Teacher;
import org.qiandaosystem.qiandaosystemsource.entity.User;
import org.qiandaosystem.qiandaosystemsource.mapper.StudentMapper;
import org.qiandaosystem.qiandaosystemsource.mapper.TeacherMapper;
import org.qiandaosystem.qiandaosystemsource.mapper.UserMapper;
import org.qiandaosystem.qiandaosystemsource.util.JwtUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class AuthService {

    private final UserMapper userMapper;
    private final TeacherMapper teacherMapper;
    private final StudentMapper studentMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;
    
    private final byte[] jwtSecretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256).getEncoded();

    @Transactional(readOnly = true)
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Transactional
    public ApiResponse<?> register(String username, String password) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(username) != null) {
            return ApiResponse.error("用户名已存在");
        }

        // 创建用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 直接存储明文密码
        user.setRole("student"); // 默认角色为student
        user.setCreatedAt(java.time.LocalDateTime.now());
        
        userMapper.insert(user);

        return ApiResponse.success("注册成功", null);
    }

    public ApiResponse<?> login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null || !password.equals(user.getPassword())) { // 直接比较明文密码
            return ApiResponse.error("用户名或密码错误");
        }

        String token = jwtUtil.generateToken(user.getUsername());
        Map<String, Object> response = new HashMap<>();
        response.put("token", token);
        response.put("username", user.getUsername());
        response.put("role", user.getRole());

        return ApiResponse.success(response);
    }

    @Transactional
    public ApiResponse<?> joinTeacher(String jwt, String teacherKey, String realName) {
        // 从JWT中获取当前登录的学生用户名
        String username = jwtUtil.extractUsername(jwt);
        User student = userMapper.findByUsername(username);
        
        if (student == null || !"student".equals(student.getRole())) {
            return ApiResponse.error("无效的学生账号");
        }

        // 检查教师是否存在
        Teacher teacher = teacherMapper.findByKey(teacherKey);
        if (teacher == null) {
            return ApiResponse.error("无效的教师邀请码");
        }

        // 检查学生是否已经加入了教师
        Student existingStudent = studentMapper.findByUserId(student.getId());
        if (existingStudent != null && existingStudent.getTeacherId() != null) {
            return ApiResponse.error("学生已加入教师班级");
        }

        // 创建或更新学生记录
        if (existingStudent == null) {
            Student newStudent = new Student();
            newStudent.setUserId(student.getId());
            newStudent.setRealName(realName);
            newStudent.setTeacherId(teacher.getUserId());
            studentMapper.insert(newStudent);
        } else {
            existingStudent.setTeacherId(teacher.getUserId());
            existingStudent.setRealName(realName);
            studentMapper.update(existingStudent);
        }

        return ApiResponse.success("成功加入教师班级", null);
    }

    private String generateToken(User user) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + 86400000); // 24小时后过期

        return Jwts.builder()
                .setSubject(user.getUsername())
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(Keys.hmacShaKeyFor(jwtSecretKey))
                .compact();
    }
} 